package stfin.install.utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

public class ConfigUtility {

	private String dataDir;
	private String configDirPath;
	private String configFilePath;
	
	private final String CONFIG_DIR_NAME = ".statizo";
	private final String CONFIG_FILE_NAME = "statizo.properties";
	private final String JAR_NAME = "statizo-financeiro-desktop-BETA.jar";
	
	private Properties configProperties;

	public static final String DATABASE_LOCATION = "statizo.database.dir";

	public ConfigUtility() throws IOException {
		
		String OS = System.getProperty("os.name");
		if(OS.contains("WIN")){
//			dataDir = System.getenv("AppData");
			dataDir = System.getenv("ProgramFiles");
		}else{
			dataDir = System.getProperty("user.home");
		}
		
		configDirPath = dataDir + System.getProperty("file.separator") + CONFIG_DIR_NAME;
		configFilePath = configDirPath + System.getProperty("file.separator") + CONFIG_FILE_NAME;
		
		loadConfigurations();
	}

	private File makeConfigDir(){
		return new File(configDirPath);
	}

	
	
	
	private void loadConfigurations() throws IOException{

		File file = makeConfigDir();

		if(!file.exists())
			file.mkdirs();

		file.mkdirs();

		File configFile = new File(file, CONFIG_FILE_NAME);

		if(!configFile.exists()){

			if(configFile.createNewFile()){

				configProperties = new Properties();
				OutputStream os = new FileOutputStream(configFile);
				configProperties.store(os, "");
				os.close(); 

			}

		}else{

			configProperties = new Properties();
			InputStream is = new FileInputStream(configFilePath);
			configProperties.load(is);
			is.close();

		}

	}

	public boolean isEmpty(){
		return this.configProperties.isEmpty();
	}
	
	public void putAndSave(String key, String value) throws IOException{
		configProperties.setProperty(key, value);
		OutputStream os = new FileOutputStream(configFilePath);
		configProperties.store(os, "");
		os.close();
	}
	
	public String get(String key){
		return configProperties.getProperty(key);
	}
	
	public String getDefaultInstalationPath(){
		return configDirPath + System.getProperty("file.separator") + JAR_NAME;
	}
	
	
	public void install(String location) throws IOException {

		InputStream jarFile = getClass().getResourceAsStream("/statizo-financeiro-desktop-BETA.jar");
		OutputStream os = new FileOutputStream(new File(location));
		IOUtils.copyLarge(jarFile, os);
		
		
	}
	
}